import React, { forwardRef, useState, useRef } from 'react';
import { Modal, ModalFuncProps, message, Input, Button } from 'antd';
import screenfull from 'screenfull';
import { getMessage, TextWidget } from '@inbiz/react';
import { InbizIcon } from '@inbiz/utils';
import ProcessIcon from '../components/ProcessIcon';
import { quickApproval } from '../service';
import view from './icons/view';
import log from './icons/log';
import deleteIcon from './icons/delete';
import approvalDone from './icons/approvalDone';
import approvalSuccess from './icons/approvalSuccess';
import approvalFail from './icons/approvalFail';
import './style.less';

const { TextArea } = Input;

const getFullScreenElement = () => {
    let managerModal = document.getElementsByClassName(
        'processCenter-quick-approval-modal-fullModal',
    )[0];
    let fullScreenElement =
        managerModal?.getElementsByClassName('ant-modal-content')[0];
    return fullScreenElement;
};

const QuickApproval: React.ForwardRefRenderFunction<
    any,
    {
        unmount: any;
        modalParams: ModalFuncProps;
        data: any[];
        goView: any;
        goGetLogInfo: any;
        afterQuickApproval: any;
        ID: string;
    }
> = (props, ref) => {
    const { unmount, modalParams, data, goView, goGetLogInfo, afterQuickApproval, ID } = props;
    const [selectedData, setSelectedData] = useState<any[]>(data);
    const [step, setStep] = useState<string>('1');
    const [loading, setLoading] = useState<boolean>(false);
    const [isFullscreen, setIsFullscreen] = useState(false);
    const [approvalResult, setApprovalResult] = useState<{ successCount: number, errorCount: number, unSupported: string[] }>({ successCount: 0, errorCount: 0, unSupported: [] });

    const instanceNumber = useRef();
    const opinions = useRef();

    const fullScreenHandleClick = () => {
        screenfull.toggle(getFullScreenElement());
        setIsFullscreen(!isFullscreen);
    };

    const doApproval = (comment: string, ids: string) => {
        setLoading(true);
        let cantQuickApprovalProcessProcessInstanceId: string[] = [];
        if (data?.length != 0) {
            cantQuickApprovalProcessProcessInstanceId = data?.filter((item) => item?.batchApproval != 1)?.map((item: { processInstanceId: string }) => item?.processInstanceId)
        }
        const _params = data?.length == 0 ? {
            assignee: ID,
            comment,
            processInstanceId: ids,
        } : {
            comment,
            taskIds: ids,
        };
        quickApproval(_params).then((res) => {
            setApprovalResult({
                successCount: res?.details?.successCount,
                errorCount: cantQuickApprovalProcessProcessInstanceId?.length + res?.details?.errorCount,
                unSupported: cantQuickApprovalProcessProcessInstanceId.concat(res?.details?.unSupported),
            });
            setStep('2');
            setLoading(false);
        }).catch((error) => {
            message.error(error?.message);
            setLoading(false);
        });
    };

    const step1Agree = () => {
        let _opinions = opinions?.current?.resizableTextArea?.textArea?.value;
        if (data?.length == 0) {
            let _instanceNumber = instanceNumber?.current?.resizableTextArea?.textArea?.value;
            if (!_instanceNumber) {
                message.error(getMessage('processCenter.enterProcessInstance'));
                return
            }
            let _instanceNumberArray = _instanceNumber?.split('\n');
            doApproval(_opinions, _instanceNumberArray?.join(','));
        } else {
            let canQuickApprovalProcess = selectedData?.filter((item) => item?.batchApproval == 1);
            if (canQuickApprovalProcess?.length == 0) {
                message.error(getMessage('processCenter.noProcessForQuickApproval'));
                return;
            };
            let _taskIdArray = canQuickApprovalProcess?.map((item) => item?.taskId);
            doApproval(_opinions, _taskIdArray?.join(','));
        }
    };

    const onFinish = () => {
        afterQuickApproval();
        unmount && unmount();
    };

    return (
        <Modal
            {...modalParams}
            width={step == '1' ? 767 : 600}
            bodyStyle={{
                height: step == '1' ? 535 : 351,
                padding: '0 20px 20px',
            }}
            className={'processCenter-quick-approval-modal-fullModal'}
            onCancel={() => {
                if (step == '2') {
                    onFinish()
                } else {
                    unmount && unmount();
                }
            }}
        >
            <>
                {
                    step == '1'
                        ?
                        <Step1
                            data={data}
                            selectedData={selectedData}
                            instanceNumber={instanceNumber}
                            opinions={opinions}
                            goView={goView}
                            goGetLogInfo={goGetLogInfo}
                            setSelectedData={setSelectedData}
                        />
                        :
                        step == '2'
                            ?
                            <Step2
                                data={data}
                                selectedData={selectedData}
                                approvalResult={approvalResult}
                                isFullscreen={isFullscreen}
                            />
                            :
                            null
                }
                <div className='processCenter-quick-approval-modal-butttons'>
                    {
                        step == '1'
                            ?
                            <div>
                                <Button style={{ marginRight: 15 }} onClick={unmount}><TextWidget>processCenter.cancel</TextWidget></Button>
                                <Button type='primary' onClick={step1Agree} loading={loading}><TextWidget>processCenter.agree</TextWidget></Button>
                            </div>
                            :
                            step == '2'
                                ?
                                <Button type='primary' onClick={onFinish}><TextWidget>processCenter.known</TextWidget></Button>
                                :
                                null
                    }
                </div>
                {
                    step == '1'
                    &&
                    <div className="processCenter-quick-approval-modal-fullscreen">
                        <InbizIcon
                            type={isFullscreen ? 'icon-huanyuan' : 'icon-ic-zuidahua'}
                            onClick={fullScreenHandleClick}
                            style={{ width: 20, height: 20 }}
                        />
                    </div>
                }
            </>
        </Modal>
    );
};

function Opinions(props: { opinions: any; }) {
    const { opinions } = props;

    return (
        <div className='processCenter-quick-approval-modal-opinions-wrapper'>
            <div className='processCenter-quick-approval-modal-opinions'>
                <div className='processCenter-quick-approval-modal-opinions-text'>
                    {getMessage('processCenter.comment') + '：'}
                </div>
                <div className='processCenter-quick-approval-modal-opinions-textarea'>
                    <TextArea placeholder={getMessage('processCenter.inputComment')} ref={opinions} maxLength={163} />
                </div>
            </div>
        </div>
    )
}

function Step1(props: { selectedData: any[]; instanceNumber: any; opinions: any; goView: any; goGetLogInfo: any; setSelectedData: any; data: any[] }) {
    const { data, selectedData, instanceNumber, opinions, goView, goGetLogInfo, setSelectedData } = props;

    const _component = () => {
        if (data?.length == 0) {
            return (
                <>
                    <div className='processCenter-quick-approval-modal-prompt'>
                        {getMessage('processCenter.inputInstance')}
                    </div>
                    <div className='processCenter-quick-approval-modal-instance'>
                        <div className='processCenter-quick-approval-modal-instance-text'>
                            {getMessage('processCenter.processInstance')}
                        </div>
                        <div className='processCenter-quick-approval-modal-instance-textarea'>
                            <TextArea placeholder={getMessage('processCenter.enterProcessInstance')} ref={instanceNumber} />
                        </div>
                    </div>
                </>
            )
        } else {
            let batchApprovalProcess = selectedData?.filter((item: { batchApproval: number; }) => item?.batchApproval == 1);
            let batchApprovalNumber = batchApprovalProcess?.length;
            const delSelectedData = (item: { taskId: string; }) => {
                let _selectedData = selectedData?.filter((item2: { taskId: string; }) => item2?.taskId != item?.taskId);
                setSelectedData(_selectedData);
            };
            const _number0 = `<span style= 'color: var(--inbiz-color-primary); margin: 0 4px' >${selectedData?.length - batchApprovalNumber}</span>`;
            const _number1 = `<span style= 'color: var(--inbiz-color-primary); margin: 0 4px' >${batchApprovalNumber}</span>`;
            const _prompt = getMessage('processCenter.dataPrompt', { 0: _number0, 1: _number1 });

            return (
                <>
                    <div className='processCenter-quick-approval-modal-prompt' dangerouslySetInnerHTML={{ __html: _prompt }} />
                    <div className='processCenter-quick-approval-modal-processes'>
                        {
                            batchApprovalProcess?.map((item: { taskId: string; processInstanceId: string; proLcon?: any; initiatorName?: string; processName?: string; summary?: string; }) => {
                                let _title = item?.initiatorName + getMessage('processCenter.initiated') + '【' + item?.processName + '】' + item?.taskId + '：' + (item?.summary || '')
                                return (
                                    <div
                                        key={item?.taskId}
                                        className='processCenter-quick-approval-modal-processes-item'
                                        title={_title}
                                    >
                                        <div className='processCenter-quick-approval-modal-processes-content'>
                                            <ProcessIcon
                                                processIconInfo={
                                                    item?.proLcon ? item?.proLcon?.trim() : 'font_family'
                                                }
                                                style={{
                                                    fontSize: 24,
                                                    marginRight: 10,
                                                }}
                                            />
                                            <div className='processCenter-quick-approval-modal-processes-item-initiatorName'>
                                                {item?.initiatorName}
                                            </div>
                                            <div className='processCenter-quick-approval-modal-processes-item-initiat'>
                                                <TextWidget>processCenter.initiated</TextWidget>
                                            </div>
                                            <div className='processCenter-quick-approval-modal-processes-item-processTask'>
                                                【{item?.processName}】
                                                {item?.processInstanceId + '：'}
                                            </div>
                                            <div className='processCenter-quick-approval-modal-processes-item-summary'>
                                                {item?.summary}
                                            </div>
                                        </div>
                                        <div className='processCenter-quick-approval-modal-processes-item-operations'>
                                            <div
                                                className="processCenter-quick-approval-modal-processes-item-operations-item"
                                                role="img"
                                                onClick={(e) => { goView(e, item); }}
                                                title={getMessage('processCenter.lookDetails')}
                                            >
                                                {React.createElement(view)}
                                            </div>
                                            <div
                                                className="processCenter-quick-approval-modal-processes-item-operations-item"
                                                role="img"
                                                onClick={(e) => { goGetLogInfo(e, item); }}
                                                title={getMessage('processCenter.viewLog')}
                                            >
                                                {React.createElement(log)}
                                            </div>
                                            <div
                                                className="processCenter-quick-approval-modal-processes-item-operations-item"
                                                role="img"
                                                onClick={() => { delSelectedData(item); }}
                                                title={getMessage('processCenter.remove')}
                                            >
                                                {React.createElement(deleteIcon)}
                                            </div>
                                        </div>
                                    </div>
                                )
                            })
                        }
                    </div>
                </>
            )
        }
    }

    return (
        <div className='processCenter-quick-approval-modal-step1'>
            {_component()}
            <Opinions opinions={opinions} />
        </div>
    )
}

function Step2(props: { data: any[]; selectedData: any[]; approvalResult: any; isFullscreen: boolean; }) {
    const { data, selectedData, approvalResult, isFullscreen } = props;
    const _all = `<span style= 'color: var(--inbiz-color-primary); margin: 0 4px' >${data?.length == 0 ? approvalResult?.successCount + approvalResult?.errorCount : selectedData?.length}</span>`;
    const _success = `<span style= 'color: var(--inbiz-color-primary); margin: 0 4px' >${approvalResult?.successCount}</span>`;
    const _fail = `<span style= 'color: var(--inbiz-color-primary); margin: 0 4px' >${approvalResult?.errorCount}</span>`;
    const _allCount = getMessage('processCenter.allCounts', { 0: _all });
    const _successCount = getMessage('processCenter.successCounts', { 0: _success });
    const _failCount = getMessage('processCenter.failCounts', { 0: _fail });

    return (
        <div className='processCenter-quick-approval-modal-step2'>
            <div className='processCenter-quick-approval-modal-step2-top'>
                <div className='processCenter-quick-approval-modal-step2-top-icon'>
                    {React.createElement(approvalDone)}
                </div>
                <div className='processCenter-quick-approval-modal-step2-top-done'>
                    <TextWidget>processCenter.approvalDone</TextWidget>
                </div>
                <div className='processCenter-quick-approval-modal-step2-top-number'>
                    <div style={{ marginRight: 15 }} dangerouslySetInnerHTML={{ __html: _allCount }} />
                    {React.createElement(approvalSuccess)}
                    <div style={{ marginRight: 15 }} dangerouslySetInnerHTML={{ __html: _successCount }} />
                    {React.createElement(approvalFail)}
                    <div dangerouslySetInnerHTML={{ __html: _failCount }} />
                </div>
            </div>
            {
                approvalResult?.errorCount > 0 && approvalResult?.unSupported?.length > 0
                &&
                <div className='processCenter-quick-approval-modal-step2-fail'>
                    <div>
                        <TextWidget>processCenter.failedProcessInstanceNumber</TextWidget>:
                    </div>
                    <div
                        style={isFullscreen ? {} : { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                        title={approvalResult?.unSupported?.join('，')}
                    >
                        {approvalResult?.unSupported?.join('，')}
                    </div>
                </div>
            }
        </div>
    )
}

export default forwardRef(QuickApproval);
